from datetime import timedelta, datetime
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
from ext import json
from google.appengine.api import users
from google.appengine.ext import db
from looptube.models import VideoInfo, RadioLog, Playlist
from looptube.utils import unescape, fetchSimilarSongs, fetchSimilarArtists, fetchArtistTrack, searchYouTubeFirstPlayableVideo
from random import randrange, seed
from urllib import urlencode
from . import commonInit


def init(request):
    # init from commonInit()
    resp = commonInit(request)
    if (HttpResponse == resp.__class__):
        return resp     # commonInit() returned HttpResponse
    contextDict = resp  # commonInit() returned dict
            
    return contextDict

def getYouTubeResultAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (not (request.GET.__contains__('song') and request.GET.__contains__('artist') and request.GET.__contains__('targetID'))):
        jsonDict = { 'success' : 0 }
    else:
        artist = unescape(request.GET['artist'])
        song = unescape(request.GET['song'])
        targetID = unescape(request.GET['targetID'])
        videoData = searchYouTubeFirstPlayableVideo("%s %s (music video OR lyrics)" % (artist, song))
        if (None == videoData):
            videoInfo = None
        else:
            videoInfo = VideoInfo.getVideoInfo("youtube", videoData['videoID'], False)
        if (None == videoInfo):
            jsonDict = { 'success' : 0 }
        else:
            jsonDict = {'success' : 1,
                        'artist' : artist,
                        'song' : song,
                        'videoID' : videoInfo.videoID,
                        'videoTitle' : videoInfo.title,
                        'thumbURL' : videoInfo.thumbURL,
                        'sourceURL' : videoInfo.sourceURL,
                        }
        jsonDict['artist'] = artist
        jsonDict['song'] = song
        jsonDict['targetID'] = targetID
        
    return HttpResponse(json.write(jsonDict), mimetype='application/json')

def getArtistTrackAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (not (request.GET.__contains__('artist') and request.GET.__contains__('targetID'))):
        jsonDict = { 'success' : 0 }
    else:
        artist = unescape(request.GET['artist'])
        targetID = unescape(request.GET['targetID'])
        result = fetchArtistTrack(artist)
        if (None == result):
            jsonDict = { 'success' : 0 }
        else:
            jsonDict = { 'success' : 1 }
            jsonDict['numResults'] = 1
            for key in result.keys():
                jsonDict[key] = result[key]
        jsonDict['targetID'] = targetID
    
    return HttpResponse(json.write(jsonDict), mimetype='application/json')

def getSimilarArtistsAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (not (request.GET.__contains__('artist'))):
        jsonDict = { 'success' : 0 }
    else:
        artist = unescape(request.GET['artist'])
        results = fetchSimilarArtists(artist)
        if (None == results):
            jsonDict = { 'success' : 0 }
        else:
            numResults = len(results)
            jsonDict = { 'success' : 1 }
            jsonDict['numResults'] = numResults
            for i in range(0, numResults):
                result = results[i]
                jsonDict[i] = result
    
    jsonDict['fromSimilarArtists'] = True
    return HttpResponse(json.write(jsonDict), mimetype='application/json')
    
def getSimilarSongsAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (not (request.GET.__contains__('song') and request.GET.__contains__('artist'))):
        jsonDict = { 'success' : 0 }
    else:
        artist = unescape(request.GET['artist'])
        song = unescape(request.GET['song'])
        results = fetchSimilarSongs(song, artist)
        if (None == results):
            jsonDict = { 'success' : 0 }
        else:
            numResults = len(results)
            if (0 == numResults):
                return HttpResponseRedirect('/channel/fetch/similarartists?'+urlencode({'artist' : artist}))
            jsonDict = { 'success' : 1 }
            jsonDict['numResults'] = numResults
            for i in range(0, numResults):
                result = results[i]
                jsonDict[i] = result
        
    return HttpResponse(json.write(jsonDict), mimetype='application/json')

def fetchAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (request.GET.__contains__('videoID')):
        videoInfo = VideoInfo.getVideoInfo('youtube', request.GET['videoID'], noshare=True, norecord=False)
        if (None == videoInfo):
            return HttpResponse(json.write({}), mimetype='application/json')
        jsonDict = {'videoID' : videoInfo.videoID,
                    'videoTitle' : videoInfo.title,
                    'thumbURL' : videoInfo.thumbURL,
                    'sourceURL' : videoInfo.sourceURL
                    }
        if (request.GET.__contains__('artist') and request.GET.__contains__('song')):
            jsonDict['artist'] = unescape(request.GET['artist'])
            jsonDict['song'] = unescape(request.GET['song'])
    else:
        channelDict = contextDict['channelDict']
        if (not (request.GET.__contains__('channel') 
                 and channelDict.has_key(request.GET['channel']))):
            return HttpResponse(json.write({}), mimetype='application/json')
        
        radiologs = RadioLog.get(channelDict[request.GET['channel']], 1)
        if (len(radiologs) == 0):
            return HttpResponse(json.write({}), mimetype='application/json')
        radiolog = radiologs[0]
        randomPlay = False
        try:
            videoTitle = radiolog.videoInfo.title
        except:
            randomPlay = True
        
        if ((request.GET.__contains__('lastID') and (radiolog.videoInfo.videoID == request.GET['lastID']))
             or request.GET.__contains__('random') or randomPlay):
            randomPlay = True
            radiologs = RadioLog.get(channelDict[request.GET['channel']], 80, offset=80)
            seed()
            while True:
                radiolog = radiologs[randrange(len(radiologs))]
                try:
                    videoTitle = radiolog.videoInfo.title
                    break
                except:
                    continue
                
        jsonDict = {'artist' : radiolog.artist,
                    'song' : radiolog.song,
                    'videoID' : radiolog.videoInfo.videoID,
                    'videoTitle' : radiolog.videoInfo.title,
                    'sourceURL' : radiolog.videoInfo.sourceURL
                    }
        if (randomPlay):
            jsonDict['randomPlay'] = 1
            
    return HttpResponse(json.write(jsonDict), mimetype='application/json')

def addPlaylistAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (not (request.GET.__contains__('title') 
             and request.GET.__contains__('store') 
             and request.GET.__contains__('videoIDs'))):
        return HttpResponseRedirect("/channel/play/highlight")

    user = users.get_current_user()
    if (bool(int(request.GET['store'])) and (None == user)):
        return HttpResponseRedirect(contextDict['loginURL']);
    
    videoIDs = unescape(request.GET['videoIDs'])
    playlist = Playlist.create(title=unescape(request.GET['title']), 
                        videoIDs=videoIDs,
                        user=user)
    return HttpResponseRedirect('/playlist/'+playlist.getKey())

def createPlaylistAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict    
    
    contextDict['pageTitle'] = _('Create Playlist')
    contextDict['playlistKey'] = 'new'
    contextDict['breadcrumbs'].append({ 'name' : _('Playlists'), 'url' : '/playlist' })
    return render_to_response('createplaylist.html', contextDict)

def editPlaylistAction(request, key):
    contextDict = {}

    siteHostname = request.get_host();
    user = users.get_current_user()
    contextDict['siteHostname'] = siteHostname
    contextDict['user'] = user
    if ('new' == key):
        contextDict['loginURL'] = users.create_login_url('http://%s/playlist/create' % siteHostname)
        if (request.GET.__contains__('save')):
            if (request.POST.__contains__('videoIDs') and request.POST.__contains__('title')):
                # save playlist
                videoIDs = unescape(request.POST['videoIDs'])
                playlist = Playlist.create(title=unescape(request.POST['title']),
                                    videoIDs=videoIDs,
                                    user=user)
                return HttpResponse('{"success":"1","key":"%s"}' % (playlist.getKey()));
            else:
                return HttpResponse('{"success":"0"}');
        else:
            contextDict['pageTitle'] = _('Create Playlist')
            videoIDs = None
    elif ('highlight' == key):
        if (request.COOKIES.__contains__('highlightVideos') 
            and (len(request.COOKIES['highlightVideos']) > 0)):
                videoIDs = unescape(request.COOKIES['highlightVideos'])
        else:
            contextDict['error'] = _("Error: You haven't highlighted any videos!")
        contextDict['pageTitle'] = _('Edit highlight video list')
    else:
        playlist = Playlist.get(key)
        if (None == playlist):
            contextDict['error'] = _('Error: Requested playlist not found!')
        else:
            if (playlist.user != user):
                contextDict['error'] = _('Error: You do not have the permission to edit the playlist!')
            else:
                if (request.GET.__contains__('delete')):
                    if (request.POST.__contains__('delete')):
                        playlist.deletePlaylist();
                        return HttpResponse('{"success":"1"}');
                    else:
                        return HttpResponse('{"success":"0"}');
                elif (request.GET.__contains__('save')):
                    if (request.POST.__contains__('videoIDs') and request.POST.__contains__('title')):
                        # save playlist
                        videoIDs = unescape(request.POST['videoIDs'])
                        playlist.putVideoIDs(videoIDs)
                        playlist.title = unescape(request.POST['title'])
                        playlist.put();
                        return HttpResponse('{"success":"1"}');
                    else:
                        return HttpResponse('{"success":"0"}');
                else:
                    videoIDs = playlist.getVideoIDs()
                    contextDict['title'] = playlist.title
        contextDict['pageTitle'] = _('Edit playlist')
            
    contextDict['key'] = key
    if (videoIDs):
        contextDict['videoIDs'] = videoIDs.split(',')
    return render_to_response('editplaylist.html', contextDict)

def getUserPlaylistAction(request, useremail):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    user = users.User(useremail)
    if (user):
        playlists = Playlist.getUserPlaylist(user)
        if (len(playlists) > 0):
            contextDict['playlists'] = playlists
    else:
        pass
    currUser = users.get_current_user()
    if (user == currUser):
        contextDict['myplaylist'] = True
    contextDict['playlistUser'] = user 
    contextDict['pageTitle'] = _('User Playlists') + ': ' + useremail
    contextDict['breadcrumbs'].append({ 'name' : _('Playlists'), 'url' : '/playlist' })
    return render_to_response('playlist.html', contextDict)
    
def playAction(request, channel, videoIDs=None, key=None):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    channelNameDict = contextDict['channelNameDict']
    if (('playlist' != channel) and (not channelNameDict.has_key(channel))):
        return HttpResponseRedirect("/")
    
    contextDict['channel'] = channel

    playlist = None
    if (channel in ['highlight', 'playlist']):
        if (('highlight' == channel) and (request.COOKIES.__contains__('highlightVideos'))):
            videoIDs = unescape(request.COOKIES['highlightVideos'])
        elif (('playlist' == channel) and key):
                try:
                    playlist = Playlist.get(key);
                except db.KindError:
                    playlist = None
                if (playlist):
                    videoIDs = playlist.getVideoIDs()
                    db.run_in_transaction(playlist.increaseCount)
        if ((None == videoIDs) or (len(videoIDs) == 0)):
            return HttpResponseRedirect("/")
        contextDict['videoIDs'] = videoIDs;            
        videoIDList = videoIDs.split(',')
        videoList = []
        for videoID in videoIDList:
            videoInfo = VideoInfo.getVideoInfo('youtube', videoID, noshare=True, norecord=False)
            if (videoInfo):
                videoList.append(videoInfo)
        contextDict['videoList'] = videoList
        contextDict['isPlaylist'] = True

    if ('playlist' == channel):
        if (key):
            contextDict['playlistKey'] = key
            contextDict['pageTitle'] = playlist.title
            contextDict['playlist'] = playlist
            user = users.get_current_user()
            if (playlist.user == user):
                contextDict['playlistEditable'] = True
        else:
            contextDict['pageTitle'] = _('Unnamed playlist')
        contextDict['breadcrumbs'].append({ 'name' : _('Playlists'), 'url' : '/playlist' })
    else:
        if ('highlight' == channel):
            contextDict['playlistKey'] = 'highlight'
            contextDict['playlistEditable'] = True
        contextDict['pageTitle'] = _('LoopTube Channel') + ': ' + channelNameDict[channel]
        contextDict['breadcrumbs'].append({ 'name' : _('Channels'), 'url' : '/channel' })
    
    if (('playlistKey' in contextDict) and (request.GET.__contains__('edit'))):
        contextDict['edit'] = True

    contextDict['playerWidth'] = 480
    contextDict['playerHeight'] = 380
    contextDict['autoPlay'] = True
    return render_to_response('channelplay.html', contextDict)
    
def indexAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    channelDesc = contextDict['channelDesc']
    channelNameDict = contextDict['channelNameDict']
    contextDict['channelList'] = [{'channel' : name, 'name' : channelNameDict[name], 'desc' : channelDesc[name]} for name in channelNameDict]
    contextDict['pageTitle'] = _('LoopTube Channels')
    return render_to_response('channellist.html', contextDict)
